package src; /**
 * Created by jinshilin on 16/12/7.
 */

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.StringUtils;

import java.io.IOException;
import java.util.Iterator;
import java.util.StringTokenizer;

public class ChildParent {

    public static int sum = 0;
    StringBuilder stringBuilder = new StringBuilder();

    public static class TokenizerMapper
            extends Mapper<Object, Text, Text, Text> {

        @Override
        public void map(Object key, Text value, Context context
        ) throws IOException, InterruptedException {
            StringTokenizer itr = new StringTokenizer(value.toString(), "\n");
            while (itr.hasMoreTokens()) {
                StringTokenizer itr1 = new StringTokenizer(itr.nextToken());
                String child = itr1.nextToken();
                String parent = itr1.nextToken();
                if (!child.equals("child")) {
                    context.write(new Text(parent), new Text("1+" + child + "+" + parent));
                    context.write(new Text(child), new Text("2+" + child + "+" + parent));
                }
            }
        }
    }

    public static class IntSumReducer
            extends Reducer<Text, Text, Text, Text> {

        @Override
        public void reduce(Text key, Iterable<Text> values,
                           Context context
        ) throws IOException, InterruptedException {
            if (sum == 0) {
                context.write(new Text("grandchild"), new Text("grandparent"));
                sum++;
            }
//            context.write(new Text("ddd"), new Text("xxx"));
            String grandchild[] = new String[10];
            String grandparent[] = new String[10];
            int grandchildCount = 0;
            int grandparentCount = 0;
            Iterator iterator = values.iterator();
            while (iterator.hasNext()) {
                String v = iterator.next().toString();
//                context.write(key, new Text(v));
//                context.write(new Text("ddd"), new Text("xxx"));
//                String[] ap = v.split("\\+");
                String[] ap = StringUtils.split(v,'+');
                if (ap != null && ap.length == 3) {
                    if (ap[0].equals("1")) {
                        grandchild[grandchildCount] = ap[1];
                        grandchildCount++;
                    } else {
                        grandparent[grandparentCount] = ap[2];
                        grandparentCount++;
                    }
                }
            }
            if (grandchildCount > 0 && grandparentCount > 0) {
                for (int m = 0; m < grandchildCount; m++) {
                    for (int n = 0; n < grandparentCount; n++) {
                        context.write(new Text(grandchild[m]), new Text(grandparent[n]));
                    }
                }
            }
        }
    }

    public static void main(String[] args) throws Exception {
        Configuration configuration = new Configuration();
        configuration.set("dfs.client.use.datanode.hostname", "true");
//        configuration.set("fs.defaultFS", "hdfs://hadoop-master:9000");//主机名访问
        configuration.set("fs.defaultFS", "hdfs://hadoop-master:9000");
//        configuration.set("dfs.nameservices", "mycluster");
//        configuration.set("dfs.ha.namenodes.mycluster", "nn1");
//        configuration.set("dfs.namenode.rpc-address.mycluster.nn1", "hadoop-master:9000");
//        configuration.set("dfs.client.failover.proxy.provider.mycluster",
//                "org.apache.hadoop.hdfs.server.namenode.ha.ConfiguredFailoverProxyProvider");

        Job job = Job.getInstance(configuration, "child parent");
        job.setJarByClass(ChildParent.class);
        job.setMapperClass(TokenizerMapper.class);
//        job.setCombinerClass(IntSumReducer.class);
        job.setReducerClass(IntSumReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        // 判断output文件夹是否存在，如果存在则删除
        Path path = new Path(args[1]);// 取第1个表示输出目录参数（第0个参数是输入目录）
        FileSystem fileSystem = FileSystem.get(configuration);
        if (fileSystem.exists(path)) {
            fileSystem.delete(path, true);// true的意思是，就算output有东西，也一带删除
        }


        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}